import React, { useCallback, useEffect, useState } from "react";
import { useLocalStorageState } from "ahooks";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import Iconfont from "@/components/IconFont";
import { Form, Input, Modal, Alert, Button, message, Tag } from "antd";
import { CloseOutlined } from "@ant-design/icons";
import { customTrimFunc } from "@/utils/utils.jsx";
import Style from "./index.module.less";
import { cloneDeep } from "lodash";
import moment from "moment";
import { useMount, useBoolean } from "ahooks";

import { CommonModal } from "@/views/components/CommonModal";
import { CommonForm } from "@/pages/OrderModule/common/components/CommonForm";
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";

import UIButton from "@/views/components/UIButton";

import request from "@/utils/request";
import { stringify } from "qs";
async function quickQueryLabelGetByCode(params) {
	return request(`/new-common/quickQueryLabel/getByCode?${stringify(params)}`, {
		loading: false
	});
}
async function quickQueryLabelSaveOrUpdate(params) {
	return request(`/new-common/quickQueryLabel/saveOrUpdate`, {
		method: "post",
		data: params,
		loading: true
	});
}

/**
 * @description: 快速搜索
 *
 * max  最多保存5个搜索条件
 * tableKey  必填，用于区分不同的搜索条件
 * searchFormInstance  必填，搜索表单
 * onQuickSearch  必填，搜索回调
 */
const isSaveApi = true;
const QuickSearch = ({ searchFormInstance, onQuickSearch, tableKey, max = 5, style }) => {
	if (!tableKey) {
		console.error("需要设置tableKey来保存列表配置");
		return <>需要设置tableKey来保存列表配置</>;
	}
	// 另存为快捷查询
	const SEARCH_TABLE_CODE = "quickSearch-" + (tableKey || "unset");

	const [form] = Form.useForm();

	const [searchList, setSearchList] = useState([]);
	// const [searchList, setSearchList] = useLocalStorageState(SEARCH_TABLE_CODE, {
	// 	defaultValue: []
	// });

	useMount(() => {
		// console.warn("QuickSearch 初始化");
		if (isSaveApi) getApi();
	});

	/**
	 * 获取【当前表格】缓存的搜索条件;
	 * @returns
	 */
	const getSearchList = useCallback(() => {
		return searchList;
	}, [searchList]);

	const saveSearchList = useCallback(list => {
		setSearchList(list);
		if (isSaveApi) saveApi(list);
	});

	const getApi = useCallback(() => {
		quickQueryLabelGetByCode({ code: SEARCH_TABLE_CODE })
			.then(res => {
				const { data, success } = res;
				if (success && data && data.param && typeof data.param === "string") {
					setSearchList(JSON.parse(data.param));
				} else {
					setSearchList([]);
				}
			})
			.catch(res => {
				setSearchList([]);
			});
	}, [SEARCH_TABLE_CODE]);

	const saveApi = useCallback(API_DATA => {
		quickQueryLabelSaveOrUpdate({ code: SEARCH_TABLE_CODE, param: JSON.stringify(API_DATA) })
			.then(res => {
				const { data, success, msg } = res;
				if (success) {
					message.success(msg || "保存成功");
				} else {
					message.warning(msg || "保存失败");
				}

				handleModalCancel();
			})
			.catch(res => {
				console.log("quickQueryLabelSaveOrUpdate res", res);
			});
	});
	const onAdd = useCallback(
		searchJson => {
			searchJson.uuid = "id" + new Date().getTime();
			const list = [...searchList, searchJson];
			saveSearchList(list);
		},
		[searchList]
	);
	const onDelete = useCallback(
		searchJson => {
			// if(currentQuery.uuid === searchJson.uuid){
			// 	setCurrentQuery({});
			// }
			const list = cloneDeep(searchList);
			const index = list.findIndex(v => v.uuid === searchJson.uuid);
			list.splice(index, 1);
			saveSearchList(list);
		},
		[searchList]
	);

	// 当前搜索条件
	const [currentQuery, setCurrentQuery] = useState({});

	// 尝试保存：弹窗--命名-校验-保存-关闭
	const trySave = useCallback(() => {
		if (getSearchList().length >= max) {
			message.warning(`搜索条件保存${max}个配置，请删除后再尝试`);
			return;
		}
		const searchQuery = searchFormInstance.getFieldsValue();

		console.log("searchQuery", searchQuery);
		setCurrentQuery(searchQuery);
		const valueLength = Object.values(searchQuery).filter(v => v !== undefined && v !== null).length;
		if (valueLength) {
			showModal();
		} else {
			// 提示 空搜索
			message.warning("当前搜索条件为空，无需保存");
		}
	}, [searchFormInstance, getSearchList, setCurrentQuery]);

	// model 逻辑
	const [isModalOpen, setIsModalOpen] = useState(false);
	const showModal = () => {
		setIsModalOpen(true);
		// 初始值
		form.setFieldsValue({
			searchName: "常用搜索条件" + (getSearchList().length + 1)
		});
	};
	const handleModalOk = useCallback(() => {
		form.submit();
	});

	const handleModalCancel = useCallback(() => {
		setIsModalOpen(false);
	});
	const handleFormFinish = useCallback(
		values => {
			onAdd({
				title: values.searchName,
				query: currentQuery
			});
		},
		[currentQuery]
	);

	const onClose = useCallback(
		searchJson => {
			Modal.confirm({
				className: "views-modal-confirm",
				centered: true,
				title: "是否删除?",
				icon: <Iconfont type="iconjingshi" />,
				okText: "确定",
				cancelText: "取消",
				onOk: () => {
					onDelete(searchJson);
				}
			});
		},
		[onDelete]
	);
	// render
	const searchListRender = useCallback(() => {
		return getSearchList().map((e, index) => {
			const key = e.title + e.uuid + index;
			return (
				<div
					key={key}
					className={Style.search_tag}
					onClick={() => {
						Object.keys(e.query).forEach(key => {
							const v = e.query[key];
							if (Array.isArray(v) && v.length === 2 && v[0] && v[1] && typeof v[0] === "string" && typeof v[1] === "string") {
								if (v[0].indexOf("T") === 10 && v[0].endsWith("Z") && v[1].indexOf("T") === 10 && v[1].endsWith("Z")) {
									e.query[key] = [moment(v[0]), moment(v[1])];
								}
							}
						});
						searchFormInstance.resetFields();
						searchFormInstance.setFieldsValue(e.query);
						onQuickSearch(e.query);
					}}
				>
					{e.title}
					<CloseOutlined
						className={Style.search_tag_close}
						onClick={ee => {
							ee.stopPropagation();
							onClose(e);
						}}
					/>
				</div>
			);
		});
	}, [getSearchList, searchFormInstance, onClose]);

	return (
		<>
			<Button className={Style.margin_right} onClick={trySave} style={style}>
				另存为快捷查询
			</Button>
			{searchListRender()}

			<CommonModal title={{ title: "另存为快捷查询条件" }} open={isModalOpen} onOk={handleModalOk} onCancel={handleModalCancel}>
				<CommonForm
					formProps={{
						form,
						onFinish: handleFormFinish
					}}
					columns={[
						{
							Component: CommonInput,
							name: "searchName",

							rules: [{ required: true, message: "请输入快捷查询名称" }],
							props: {
								placeholder: "必填",
								"aria-required": true,
								showCount: true,
								maxLength: 10
							}
						}
					]}
				></CommonForm>
			</CommonModal>
		</>
	);
};
export default React.memo(QuickSearch, () => {
	return true;
});
